import { defineStore } from 'pinia'
import { wxLogin, getRouters, getInfo, login } from '@/api/login.js';

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      id: '',
      nickname: '',
      avatar: '',
      phone: '',
      email: '',
      vipLevel: 0,
      isLogin: false
    },
    token: '',
    
    // 我的简历列表
    myResumes: [],
    
    // 我的收藏列表
    favorites: [],
    
    // 我的订单列表
    orders: [],
    
    // 应用设置
    settings: {
      notification: true, // 通知开关
      remindToComplete: true, // 提醒完善简历
      darkMode: false, // 深色模式
      autoSync: true, // 自动同步
      language: 'zh-cn' // 语言设置
    }
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token && !!state.userInfo.id,
    
    // 获取用户信息
    getUserInfo() {
      return this.userInfo
    },
    
    // 获取我的简历列表
    getMyResumes() {
      return this.myResumes
    },
    
    // 获取我的收藏列表
    getFavorites() {
      return this.favorites
    },
    
    // 获取我的订单列表
    getOrders() {
      return this.orders
    }
  },
  
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = {
        ...this.userInfo,
        ...userInfo,
        isLogin: true
      }
    },
    
    // 设置登录凭证
    setToken(token) {
      this.token = token
      // 保存到本地
      uni.setStorageSync('token', token)
    },
    
    // 登录处理
    login(user, token) {
      this.setUserInfo(user)
      this.setToken(token)
      
      // 保存到本地
      this.saveToStorage()
    },
    
    // 退出登录
    logout() {
      // 重置用户信息
      this.userInfo = {
        id: '',
        nickname: '',
        avatar: '',
        phone: '',
        email: '',
        vipLevel: 0,
        isLogin: false
      }
      
      // 重置Token
      this.token = ''
      
      // 保留用户数据但清除登录状态
      // 注意：在实际应用中，可以选择是否清除用户的收藏、订单等数据
      
      // 清除本地存储
      uni.removeStorageSync('token')
      
      // 更新存储的用户数据
      this.saveToStorage()
    },
    
    // 加载用户信息
    loadFromStorage() {
      try {
        const userData = uni.getStorageSync('userData')
        const token = uni.getStorageSync('token')
        
        if (userData) {
          const data = JSON.parse(userData)
          
          if (data.userInfo) this.userInfo = data.userInfo
          if (data.myResumes) this.myResumes = data.myResumes
          if (data.favorites) this.favorites = data.favorites
          if (data.orders) this.orders = data.orders
          if (data.settings) this.settings = data.settings
        }
        
        if (token) {
          this.token = token
        }
      } catch (e) {
        console.error('Failed to load user data from storage', e)
      }
    },
    
    // 保存到本地存储
    saveToStorage() {
      try {
        const userData = {
          userInfo: this.userInfo,
          myResumes: this.myResumes,
          favorites: this.favorites,
          orders: this.orders,
          settings: this.settings
        }
        
        uni.setStorageSync('userData', JSON.stringify(userData))
        uni.setStorageSync('token', this.token)
      } catch (e) {
        console.error('Failed to save user data to storage', e)
      }
    },
    
    // 更新用户信息
    updateUserInfo(info) {
      this.userInfo = { ...this.userInfo, ...info }
      this.saveToStorage()
    },
    
    // 添加新简历
    addResume(resume) {
      this.myResumes.push({
        id: Date.now().toString(),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        ...resume
      })
      this.saveToStorage()
    },
    
    // 更新简历
    updateResume(id, resume) {
      const index = this.myResumes.findIndex(item => item.id === id)
      if (index !== -1) {
        this.myResumes[index] = {
          ...this.myResumes[index],
          ...resume,
          updatedAt: new Date().toISOString()
        }
        this.saveToStorage()
      }
    },
    
    // 删除简历
    deleteResume(id) {
      this.myResumes = this.myResumes.filter(item => item.id !== id)
      this.saveToStorage()
    },
    
    // 添加收藏
    addFavorite(item) {
      if (!this.favorites.some(f => f.id === item.id)) {
        this.favorites.push({
          ...item,
          addedAt: new Date().toISOString()
        })
        this.saveToStorage()
      }
    },
    
    // 删除收藏
    removeFavorite(id) {
      this.favorites = this.favorites.filter(item => item.id !== id)
      this.saveToStorage()
    },
    
    // 添加订单
    addOrder(order) {
      this.orders.push({
        id: Date.now().toString(),
        createdAt: new Date().toISOString(),
        status: 'paid', // pending, paid, cancelled, refunded
        ...order
      })
      this.saveToStorage()
    },
    
    // 更新订单状态
    updateOrderStatus(id, status) {
      const index = this.orders.findIndex(item => item.id === id)
      if (index !== -1) {
        this.orders[index].status = status
        this.saveToStorage()
      }
    },
    
    // 更新设置
    updateSettings(settings) {
      this.settings = { ...this.settings, ...settings }
      this.saveToStorage()
    }
  }
}) 